/**
 * Created by wd14931 on 2015/12/7.
 * 异步引入js,css
 */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define([], factory);
    } else if (typeof module === 'object' && module.exports) {
        module.exports = factory();
    } else {
        root.asynLoad = factory();
    }
}(this, function () {

    var asynLoad = {

        loadScript: function(cfg){

            var that = this,
                url = cfg.url,
                cssUrl = cfg.cssUrl || null,
                callback = cfg.callback || null;

            var _append = function(url, callback){

                if($('script[src="' + url + '"]').length){
                    return;
                }

                var script = document.createElement("script");

                script.type = "text/javascript";
                script.src = url;
                document.body.appendChild(script);

                if(callback){
                    script.onload = callback;
                }
            };

            if(cssUrl)
                that.loadStyles({url: cssUrl, callback: function(){
                    _append(url, callback);
                }});
            else
                _append(url, callback);
        },

        loadStyles: function(cfg){

            var url = cfg.url,
                callback = cfg.callback || null;

            var _append = function(url, callback){

                if($('link[href="' + url + '"]').length){
                    return;
                }

                var link = document.createElement("link");

                link.rel = "stylesheet";
                link.type = "text/css";
                link.href = url;
                var head = document.getElementsByTagName("head")[0];
                head.appendChild(link);

                if(callback){
                    link.onload = callback;
                }
            };

            _append(url, callback);
        }
    };

    return asynLoad;
}));


